package com.czy.owner.ui.garage;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.adapter.BaseRecyclerAdapter;
import com.czy.owner.adapter.PickBrandAdapter;
import com.czy.owner.adapter.SearchHistoryAdapter;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.DbHelper;
import com.czy.owner.db.SearchTable;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.CarBrandModel;
import com.czy.owner.global.Constants;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.disk.DiskLruCacheHelper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by King on 2016/7/21 0021.
 */
public class SearchBrandActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.et_brand_search_keyword)
    EditText etKeyword;
    @BindView(R.id.iv_brand_search_clean)
    ImageView ivClean;
    @BindView(R.id.tv_brand_search_close)
    TextView tvCLose;
    @BindView(R.id.ll_brand_search_history_title)
    LinearLayout llHistoryTitle;
    @BindView(R.id.tv_brand_search_title)
    TextView tvTitle;
    @BindView(R.id.iv_remove_history)
    ImageView ivRemoveHistory;
    @BindView(R.id.rv_brand_search_result)
    RecyclerView rvResult;

    private boolean isSearching = false;
    private DbManager db = null;
    private List<SearchTable> historyList = new ArrayList<>();
    private List<CarBrandModel> brandList = new ArrayList<>();
    private DiskLruCacheHelper cacheHelper ;
    private boolean isNeedReturnResult = false;


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_brand_search;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {

    }

    @Override
    protected void updateViews() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 获取编辑框焦点
        etKeyword.setFocusable(true);
        isNeedReturnResult  = getIntent().getBooleanExtra(PickBrandActivity.START_FLAG, false);
        MyLog.d("RAVEN","search  needResult = " + isNeedReturnResult);
        //打开软键盘
        /*InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);*/
        db = DbHelper.getInstance().getDb();
        ivClean.setOnClickListener(this);
        tvCLose.setOnClickListener(this);
        etKeyword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    searchBrand();
                }
                return false;
            }
        });
        etKeyword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (etKeyword.getText().toString().length() > 0) {
                    ivClean.setVisibility(View.VISIBLE);
                } else {
                    ivClean.setVisibility(View.GONE);
                }
            }
        });
        etKeyword.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {// 修改回车键功能
                    searchBrand();
                }
                return false;
            }
        });

        ivRemoveHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    WhereBuilder builder = WhereBuilder.b("searchtype", "=", SearchTable.SEARCH_TYPE_BRAND).and("useraccount", "=", UserHelper.getInstance().getUserAccount());
                    db.delete(SearchTable.class, builder);
                } catch (DbException e) {
                    e.printStackTrace();
                }
                initKeyWordHistory();
            }
        });
        initKeyWordHistory();
    }

    private void initKeyWordHistory() {
        tvTitle.setText(getResources().getString(R.string.search_history));
        try {
            historyList = db.selector(SearchTable.class)
                    .where("searchtype", "=", SearchTable.SEARCH_TYPE_BRAND)
                    .and("useraccount", "=", UserHelper.getInstance().getUserAccount())
                    .orderBy("searchTime", true)
                    .limit(10)
                    .findAll();

        } catch (DbException e) {
            e.printStackTrace();
        }
        if (historyList!= null && historyList.size() > 0) {
            llHistoryTitle.setVisibility(View.VISIBLE);
            tvTitle.setVisibility(View.VISIBLE);
            rvResult.setVisibility(View.VISIBLE);
            ivRemoveHistory.setVisibility(View.VISIBLE);
            SearchHistoryAdapter mSearchAdapter = new SearchHistoryAdapter(this, historyList);
            mSearchAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<SearchTable>() {
                @Override
                public void onItemClick(int position, SearchTable o, View view) {
                    etKeyword.setText(o.getKeyWord());
                    searchBrand();
                }
            });
            RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
            rvResult.setLayoutManager(layoutManager);
            rvResult.setAdapter(mSearchAdapter);
            rvResult.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));
        } else {
            llHistoryTitle.setVisibility(View.GONE);
            tvTitle.setVisibility(View.GONE);
            rvResult.setVisibility(View.GONE);
            ivRemoveHistory.setVisibility(View.GONE);
        }
    }

    private void searchBrand() {
        if (isSearching) return;
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        boolean isOpen = imm.isActive();
        if (isOpen) {
            imm.hideSoftInputFromWindow(etKeyword.getWindowToken(), 0);
        }
        final String keyWord = etKeyword.getText().toString().toString().trim();
        if (TextUtils.isEmpty(keyWord)) {
            return;
        }
        isSearching = true;
        mLoadView.ShowLoadView(getResources().getString(R.string.refresh_loading));
        final RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_CAR_BRAND_SEARCH);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(this).getSession());
        params.addBodyParameter("likeName", keyWord);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String data = PhoneUtils.checkResponseFlag(SearchBrandActivity.this, result);
                llHistoryTitle.setVisibility(View.VISIBLE);
                ivRemoveHistory.setVisibility(View.GONE);
                if (data != null) {
                    saveSearchKeyWord(keyWord);
                    tvTitle.setText(getResources().getString(R.string.search_result));
                    tvTitle.setVisibility(View.VISIBLE);
                    try {
                        Gson gson = new GsonBuilder().create();
                        brandList = gson.fromJson(data, new TypeToken<List<CarBrandModel>>() {
                        }.getType());
                    } catch (Exception e) {

                    }
                    if(brandList.size()>0){
                        rvResult.setVisibility(View.VISIBLE);

                        PickBrandAdapter mBrandAdapter = new PickBrandAdapter(SearchBrandActivity.this, brandList);
                        mBrandAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<CarBrandModel>() {
                            @Override
                            public void onItemClick(int position, CarBrandModel o, View view) {
//                                Intent intent = new Intent();
//                                intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, o);
//                                setResult(Constants.ACTIVITY_RESULT_CODE_CAR_ADD, intent);
//                                finish();
                                dealBrand(o);
                            }
                        });
                        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(SearchBrandActivity.this);
                        rvResult.setLayoutManager(layoutManager);
                        rvResult.setAdapter(mBrandAdapter);
                        rvResult.addItemDecoration(new RecycleViewDivider(SearchBrandActivity.this, LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));

                    }else{
                        tvTitle.setText(getResources().getString(R.string.search_result_none));
                        rvResult.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                isSearching = false;
                mLoadView.CancleLoadView();
            }
        });
    }

    private void dealBrand(CarBrandModel carBrandModel){
        getPLData(carBrandModel);//获取下一级的数据，排量。没有则跳转编辑页面
    }

    private void getPLData(final CarBrandModel carBrandModel){
        final RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_CAR_BRAND_ALL_ATTR);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(SearchBrandActivity.this).getSession());
        params.addBodyParameter("carBrandId", "" + carBrandModel.getCarBrandId());
        mLoadView.ShowLoadView();
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String data = PhoneUtils.checkResponseFlag(SearchBrandActivity.this, result);
                if (data != null) {
                    try {
                        Gson gson = new GsonBuilder().create();
                        List<CarBrandModel> carPL = gson.fromJson(data, new TypeToken<List<CarBrandModel>>() {
                        }.getType());

                        if(carPL != null && carPL.size() > 0){//有下一级数据
                            MyLog.d("RAVEN","searchpage isNeedRESULT = " + isNeedReturnResult);
                            Intent intent = new Intent(SearchBrandActivity.this,SelCarOtherAttrActivity.class);
                            try{
                                String[] brandName = carBrandModel.getChName().split("_");
                                carBrandModel.setChName(brandName[brandName.length-1]);
                            }catch (Exception e){
                                MyLog.e("RAVEN","e=" + e.getMessage());
                            }
                            intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, carBrandModel);
                            intent.putExtra(SelCarOtherAttrActivity.FIRST_LIST_DATA, (Serializable) carPL);
                            intent.putExtra(SelCarOtherAttrActivity.IS_NEED_RESULT_DATA, isNeedReturnResult);
                            if(isNeedReturnResult) {
                                startActivityForResult(intent,PickBrandActivity.REQUEST_BRAND_CODE);
                            }else {
                                intent.putExtra(EditCarActivity.ACTION_TYPE_KEY, EditCarActivity.ACTION_TYPE.ADD);
                                startActivityForResult(intent, 0);
                            }
                        }else {//没下级数据了
                            try{
                                String[] brandName = carBrandModel.getChName().split("_");
                                carBrandModel.setChName(brandName[brandName.length-1]);
                            }catch (Exception e){
                                MyLog.e("RAVEN","e=" + e.getMessage());
                            }


                            if(isNeedReturnResult){//重设车
                                MyLog.d("RAVEN","搜索页重设车 三级");
                                Intent intent = new Intent();
                                intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, carBrandModel);
                                SearchBrandActivity.this.setResult( Constants.ACTIVITY_RESULT_CODE_RESET_BRAND, intent);
                                SearchBrandActivity.this.finish();
                            } else {
                                //添加车
                                Intent intent = new Intent(SearchBrandActivity.this, EditCarActivity.class);
                                intent.putExtra(EditCarActivity.ACTION_TYPE_KEY, EditCarActivity.ACTION_TYPE.ADD);
                                intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, carBrandModel);
                                SearchBrandActivity.this.startActivityForResult(intent, 0);
                            }
                        }

                    } catch (Exception e) {

                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }

    private void saveSearchKeyWord(String keyWord) {
        try {
            SearchTable tmpSearch = db.selector(SearchTable.class).where("keyword", "=", keyWord).and("searchtype", "=", SearchTable.SEARCH_TYPE_BRAND).and("useraccount", "=", UserHelper.getInstance().getUserAccount()).findFirst();

            if (tmpSearch == null) {
                SearchTable search = new SearchTable();
                search.setKeyWord(keyWord);
                search.setSearchType(SearchTable.SEARCH_TYPE_BRAND);
                search.setSearchTime(System.currentTimeMillis());
                search.setUserAccount(UserHelper.getInstance().getUserAccount());
                db.saveOrUpdate(search);
            } else {
                tmpSearch.setKeyWord(keyWord);
                tmpSearch.setSearchType(SearchTable.SEARCH_TYPE_BRAND);
                tmpSearch.setSearchTime(System.currentTimeMillis());
                tmpSearch.setUserAccount(UserHelper.getInstance().getUserAccount());
                db.update(tmpSearch);
            }

        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_brand_search_clean:
                etKeyword.setText("");
                initKeyWordHistory();
                break;
            case R.id.tv_brand_search_close:
                finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (requestCode == 0 && resultCode == Constants.ACTIVITY_RESULT_CODE_CAR_ADD) {
            setResult(Constants.ACTIVITY_RESULT_CODE_CAR_ADD);
            finish();
        }

        if (requestCode == PickBrandActivity.REQUEST_BRAND_CODE && resultCode == Constants.ACTIVITY_RESULT_CODE_RESET_BRAND) {
            String pl = data.getStringExtra("selected_car_pl");
            String nf = data.getStringExtra("selected_car_nf");
            CarBrandModel selectedCarModel = (CarBrandModel) data.getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY);
            Intent intent = new Intent();
            intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, selectedCarModel);
            intent.putExtra("selected_car_pl", pl);
            intent.putExtra("selected_car_nf", nf);
            setResult(Constants.ACTIVITY_RESULT_CODE_RESET_BRAND, intent);
            finish();
        }
    }
}

